package com.hos.utils;

import com.auth0.jwt.*;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: 陈海彬
 * @date: Created in 2023/12/7 17:32
 * @description: jwt生成工具类
 * @modified By:
 * @version: 1.0
 */

public class JwtUtils {


    /**
     * @param username 加密的用户名
     * @return java.lang.String
     * @create by: 陈海彬
     * @description: 生成JWT令牌
     * @create time: 2023/12/7 17:34
     */
    public static String create(String username) {
        Map<String, Object> head = new HashMap<>();
        head.put("alg", "HS256");
        head.put("typ", "JWT");

        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.MINUTE, 30);
        Date expiresDate = nowTime.getTime();
        String token = JWT.create()
                .withHeader(head)// 设置JWT头信息
                .withIssuedAt(new Date())    // 发行时间
                .withExpiresAt(expiresDate)  // 过期时间
                .withClaim("username", username)
                .sign(Algorithm.HMAC256("aaa-hos-parent"));
        return token;
    }

    /**
     * @param token token信息
     * @return boolean
     * @create by: 陈海彬
     * @description: 校验令牌
     * @create time: 2023/12/7 17:35
     */
    public static boolean verifyToken(String token) {

        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256("aaa-hos-parent")).build();
            jwt = verifier.verify(token);
            return true;
        } catch (Exception e) {
            // 效验失败
            e.printStackTrace();
        }
        return false;
    }

    /**
     * @param token token令牌
     * @return java.lang.String
     * @create by: 陈海彬
     * @description: 解析token
     * @create time: 2023/12/7 17:35
     */
    public static String getClaimByName(String token) {
        return JWT.decode(token).getClaim("username").asString();
    }
}